import { Box, Flex } from '@chakra-ui/react'
import { Button } from '@pancakeswap/uikit'
import Decimal from 'decimal.js'
import { useEffect, useState } from 'react'
import { useSwapStore } from '@/features/Swap/useSwapStore'
import { useDisclosure } from '@/hooks/useDelayDisclosure'
import MoreListControllers from '@/icons/misc/MoreListControllers'
import { useLiquidityStore } from '@/store'
import { colors } from '@/theme/cssVariables'
import { SlippageSettingModal } from './SlippageSettingModal'

export function SlippageAdjuster({ variant = 'swap', onClick }: { variant?: 'swap' | 'liquidity'; onClick?: () => void }) {
  const { isOpen, onClose, onToggle } = useDisclosure()
  const swapSlippage = useSwapStore((s) => s.slippage)
  const liquiditySlippage = useLiquidityStore((s) => s.slippage)
  const isSwap = variant === 'swap'
  const slippage = isSwap ? swapSlippage : liquiditySlippage
  const [currentSlippage, setCurrentSlippage] = useState<string | undefined>()
  const [isWarn, setIsWarn] = useState(false)

  useEffect(() => {
    const slippageDecimal = new Decimal(slippage * 100)
    setCurrentSlippage(slippageDecimal.toDecimalPlaces(2).toString())
    const warn = isSwap && (slippageDecimal.gt('0.5') || slippageDecimal.lt('0.1'))
    setIsWarn(warn)
  }, [slippage, isSwap])
  const handleOnClick = () => {
    onToggle()
  }
  return (
    <>
      <Flex align="center" onClick={onClick || handleOnClick}>
        <Button
          size="xs"
          height="fit-content"
          py={1}
          px={2}
          borderRadius="12px"
          border={isWarn ? `1px solid ${colors.semanticWarning}` : undefined}
          startIcon={
            <Box>
              <MoreListControllers
                width="14"
                height="14"
                className="chakra-icon chakra-icon-hover"
                color={isWarn ? colors.semanticWarning : colors.primary60}
              />
            </Box>
          }
          variant={isWarn ? 'danger' : 'primary60'}
        >
          {currentSlippage}%
        </Button>
      </Flex>
      <SlippageSettingModal variant={variant} isOpen={isOpen} onClose={onClose} />
    </>
  )
}
